package top.kikt.book.core.template

import top.kikt.book.core.base.IBookHandler
import top.kikt.book.core.base.ILogger
import top.kikt.book.core.entity.BookEntity
import java.io.File

interface OutputTemplate : ILogger {

    fun write(bookHandler: IBookHandler, entity: BookEntity, outputPath: String): File

    fun fileExt(): String

    fun readContent(bookHandler: IBookHandler, file: File): String {
        val srcContent = file.readText()
        return bookHandler.replaceWatermark(srcContent).toBookText()
    }

    fun String.toBookText(): String {
        return this.replace("\r\n", "\n").replace("\r", "\n")
            .split("\n")
            .map { it.trim() }
            .map { it.replace(" ", "") }
            .filter { it.isNotEmpty() }
            .joinToString("\n")
    }

    fun getOutputFilePath(bookHandler: IBookHandler, entity: BookEntity, outputPath: String): String {
        val name = entity.metaEntity.name
        val suffix = bookHandler.currentHost.removePrefix("www.")
        val fileName = "${name}_$suffix.${fileExt()}"

        return "$outputPath/$fileName"
    }
}